<?php

/**
 * viewport actions.
 *
 * @package    worldmap
 * @subpackage viewport
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class viewportActions extends sfActions
{
   /**
    * Executes index action
    *
    * @param sfRequest $request A request object
    */
    public function executeIndex(sfWebRequest $request)
    {
        $this->searchForm = new searchForm();
    }

    protected function ensureXmlHttpRequest($request)
    {
        if (!sfConfig::get('sf_web_debug')
            && !$request->isXmlHttpRequest()
            && !$request->getParameter('isXMLHttpRequest')
        ) {
            $this->redirect('homepage');
        }

        return true;
    }

    protected function returnJson($output)
    {
        if (!sfConfig::get('sf_web_debug')) {
            $response = sfContext::getInstance()->getResponse();
            $response->setContentType('application/json');
            $this->getResponse()->setContent(json_encode($output));
            return sfView::NONE;
        }

        $this->setLayout('layout');
        $this->output = $output;
        $this->setTemplate('renderJson');
    }

    public function executeGetBubbleData(sfWebRequest $request)
    {
        $this->ensureXmlHttpRequest($request);

        $lat_min = $request->getParameter('lat_min');
        $lat_max = $request->getParameter('lat_max');
        $lng_min = $request->getParameter('lng_min');
        $lng_max = $request->getParameter('lng_max');

        $entities = Doctrine::getTable('entity')
          ->createQuery('e')
          ->select('e.type, e.id')
          ->where('e.lat BETWEEN ? AND ?', array($lat_min, $lat_max))
          ->addWhere('e.lng BETWEEN ? AND ?', array($lng_min, $lng_max))
          ->execute(array(), Doctrine::HYDRATE_ARRAY);

        $entity_ids = array();
        foreach ($entities as $entity) {
            $entity_ids[$entity['type']][] = $entity['id'];
        }

        $output = array();
        foreach ($entity_ids as $type => $entities) {
            $entities = Doctrine::getTable($type)
              ->createQuery('e')
              ->whereIn('e.entity_id', $entities)
              ->execute(array(), Doctrine::HYDRATE_ARRAY);

            foreach ($entities as $entity) {
                $output[$entity['entity_id']] = $this->getPartial('renderBubble', array('entity' => $entity));
            }
        }

        return $this->returnJson($output);
    }

    public function executeFilterData(sfWebRequest $request)
    {
        $this->ensureXmlHttpRequest($request);

        $output = array();

        $this->searchForm = new searchForm();
        $this->searchForm->bind($request->getParameter('filter'), $request->getFiles('filter'));

        if ($this->searchForm->isValid()) {
            $filter = $this->searchForm->getValues();

            if (empty($filter['types']) || in_array('user', $filter['types'])) {
                $query = Doctrine::getTable('user')
                  ->createQuery('u')
                  ->select('u.entity_id AS id');

                if (!empty($filter['text'])) {
                    $query->addWhere('u.name LIKE ?', '%'.$filter['text'].'%');
                    $query->orWhere('u.address LIKE ?', '%'.$filter['text'].'%');
                    $query->orWhere('u.email LIKE ?', '%'.$filter['text'].'%');
                    $query->orWhere('u.description LIKE ?', '%'.$filter['text'].'%');
                    $query->orWhere('u.url LIKE ?', '%'.$filter['text'].'%');
                    $query->whereParenWrap();
                }

                if (isset($filter['has_firmwarekit'])) {
                    $query->addWhere('u.has_firmwarekit = ?', (bool)$filter['has_firmwarekit']);
                }

                if (isset($filter['controller_list'])) {
                    foreach ($filter['controller_list'] as $key => $controller) {
                        $query->innerJoin("u.controllers uc$key");
                        $query->andWhere("uc$key.controller_id = ?", $controller);
                    }
                }

                $users = $query->execute(array(), Doctrine::HYDRATE_NONE);
                foreach ($users as $key => $value) {
                    $output[$key] = reset($value);
                }
            }

            if (empty($filter['types']) || in_array('store', $filter['types'])) {
                $query = Doctrine::getTable('store')
                  ->createQuery('s')
                  ->select('s.entity_id AS id');

                if (!empty($filter['text'])) {
                    $query->addWhere('s.name LIKE ?', '%'.$filter['text'].'%');
                    $query->orWhere('s.address LIKE ?', '%'.$filter['text'].'%');
                    $query->orWhere('s.email LIKE ?', '%'.$filter['text'].'%');
                    $query->orWhere('s.description LIKE ?', '%'.$filter['text'].'%');
                    $query->orWhere('s.url LIKE ?', '%'.$filter['text'].'%');
                    $query->whereParenWrap();
                }

                if (isset($filter['manufacturer_list'])) {
                    foreach ($filter['manufacturer_list'] as $key => $manufacturer) {
                        $query->innerJoin("s.manufacturers sm$key");
                        $query->andWhere("sm$key.manufacturer_id = ?", $manufacturer);
                    }
                }

                $stores = $query->execute(array(), Doctrine::HYDRATE_NONE);
                foreach ($stores as $key => $value) {
                    $output[$key] = reset($value);
                }
            }

            if (empty($filter['types']) || in_array('event', $filter['types'])) {
                $query = Doctrine::getTable('event')
                  ->createQuery('e')
                  ->select('e.entity_id AS id');

                if (!empty($filter['text'])) {
                    $query->addWhere('e.name LIKE ?', '%'.$filter['text'].'%');
                    $query->orWhere('e.address LIKE ?', '%'.$filter['text'].'%');
                    $query->orWhere('e.description LIKE ?', '%'.$filter['text'].'%');
                    $query->orWhere('e.url LIKE ?', '%'.$filter['text'].'%');
                    $query->whereParenWrap();
                }

                if (isset($filter['startdate'])) {
                    $query->andWhere('e.startdate >= ?', $filter['startdate']);
                }

                if (isset($filter['enddate'])) {
                    $query->andWhere('e.enddate <= ?', $filter['enddate']);
                }

                $events = $query->execute(array(), Doctrine::HYDRATE_NONE);
                foreach ($events as $key => $value) {
                    $output[$key] = reset($value);
                }
            }
        }

        return $this->returnJson($output);
    }

    public function executeGetDetails(sfWebRequest $request)
    {
        $this->ensureXmlHttpRequest($request);

        $id = $request->getParameter('id');
        $entity = Doctrine::getTable('entity')->find(array($id));
        $this->forward404Unless($entity);

        $type = $entity->getType();
        $entity_id = $entity->getId();

        $entity = Doctrine::getTable($type)
          ->createQuery('e')
          ->where('e.entity_id = ?', $entity->getId())
          ->fetchOne();
        $this->forward404Unless($entity);

        $output = $this->getPartial('renderDetail', array('entity' => $entity->toArray()));

        return $this->returnJson($output);
    }
}
